
#include <algorithm>

#include <stdio.h>

#include "eventqueue.h"
#include "event.h"

class __Event_Time_Comp
{
public:
	bool operator () (Event *event1, Event *event2)
	{return event1->getTime() > event2->getTime();};
};

EventQueue::EventQueue()
	: total_count_(0)
	, max_size_(0)
{
	event_queue_.reserve( 1024*1024 );
}

EventQueue::~EventQueue()
{
	fprintf(stderr, "\nEventQueue capacity %u total:%u max_size:%u\n", event_queue_.capacity(), total_count_, max_size_);
	clearEventQueue();
}

void EventQueue::insertEvent( Event *e )
{
	event_queue_.push_back( e );
	std::push_heap(event_queue_.begin(), 
		event_queue_.end(), __Event_Time_Comp());
	total_count_++;
	if ( event_queue_.size()>max_size_ ) max_size_ = event_queue_.size();
}

Event* EventQueue::nextEvent()
{
	if ( empty() ) return NULL;
	Event *event = event_queue_.front();
	std::pop_heap(event_queue_.begin(), 
		event_queue_.end(), __Event_Time_Comp());
	event_queue_.pop_back();
	return event;
}

bool EventQueue::empty() const
{
	return event_queue_.empty();
}

void EventQueue::clearEventQueue()
{
	std::for_each( event_queue_.begin(), event_queue_.end(),
			ReleaseObject() );
	event_queue_.clear();
}


